<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Index extends MY_Controller {
    private $per_page  = '10';
    private $prev_link  = 'Prev';
    private $next_link  = 'Next';
    private $workerstate = array("overseas","singapore");
    
    public function __construct(){
        parent::__construct();
        $this->load->model('index_model');
        $this->load->model('user_model');
        $this->load->model('profile_model');
    }
    
    public function index(){
        if($this->is_logged_in()){
            $state = 0;
            $condition = "";
            if($_GET){
                $state = $this->input->get('state');
                $condition = $this->input->get('condition');
            }else if($_POST){
                $state = $this->input->post('state');
                $condition = $this->input->post('condition');
            }
            $config = array();
            $config['per_page']    = $this->per_page;         //每页显示的数据数
            $current_page          = intval($this->input->get_post('per_page',true));  //获取当前分页页码数
            if(0 == $current_page){
               $current_page = 1;
            }
            $ordername = ($this->input->post('ordername') != NULL&&$this->input->post('ordername') != "")
                    ?$this->input->post('ordername'):
                        (($this->input->get('ordername') != NULL&&$this->input->get('ordername') != "")
                            ?$this->input->get('ordername'):"updatetime desc");
            $offset   = ($current_page - 1 ) * $config['per_page'];          //设置偏移量 限定 数据查询 起始位置（从 $offset 条开始）       
            $candidate  = $this->index_model->get_candidate($offset,$config['per_page'],$ordername,$condition,$state);
            $config['base_url']           = base_url('index/index?').'condition='.$condition."&ordername=".$ordername."&"."&state=".$state."&";
            $config['prev_link']          = $this->prev_link;
            $config['next_link']          = $this->next_link;
            $config['total_rows']         = $candidate['total'];         //获取查询数据的总记录数
            $config['use_page_numbers']   = TRUE;            //默认分页URL中是显示每页记录数,启用use_page_numbers后显示的是当前页码
            $config['page_query_string']  = TRUE;            //把 $config['enable_query_strings'] 设置为 TRUE，链接将自动地被用查询字符串（url中的参数）重写。        
            $this->pagination->initialize($config);
            foreach ($candidate['res'] as $key => $value) {
                $value['location'] = $this->workerstate[$value['location']>1?1:$value['location']];
                $candidate['res'][$key] = $value;
            }

            $data = array(
                'candidates'  => $candidate['res'],
                'total'   => $candidate['total'],
                'current_page' => $current_page,
                'per_page'  => $config['per_page'],
                'page'   => $this->pagination->create_links(),
                'condition'  =>  $condition,
                'ordername'=>$ordername,
                'state'=>$state
            );
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/candidate',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }

    public function export2excel(){
        if($this->is_logged_in()){
            $state = 0;
            $condition = "";
            if($_GET){
                $state = $this->input->get('state');
                $condition = $this->input->get('condition');
            }else if($_POST){
                $state = $this->input->post('state');
                $condition = $this->input->post('condition');
            }
            $config = array();
            $config['per_page']    = $this->per_page;         //每页显示的数据数
            $current_page          = intval($this->input->get_post('per_page',true));  //获取当前分页页码数
            if(0 == $current_page){
               $current_page = 1;
            }
            $ordername = ($this->input->post('ordername') != NULL&&$this->input->post('ordername') != "")
                    ?$this->input->post('ordername'):
                        (($this->input->get('ordername') != NULL&&$this->input->get('ordername') != "")
                            ?$this->input->get('ordername'):"updatetime desc");
            $offset   = ($current_page - 1 ) * $config['per_page'];          //设置偏移量 限定 数据查询 起始位置（从 $offset 条开始）       
            $candidate  = $this->index_model->get_candidate_export($ordername,$condition,$state);
            $arrStatus[0] = 'Normal';
            $arrStatus[1] = 'In Provile';
            $arrStatus[4] = 'Archived';
            
            foreach ($candidate as $key => $value) {
                $cand[0] = $value['name'];
                $cand[1] = $value['gender']==1?"M":"F";
                $cand[2] = $value['nationality']==1?"Malaysia":($value['nationality']==2?"China":($value['nationality']==3?"Vietnam":($value['nationality']==4?"Myanmar":$value['nationality'])));
                $cand[3] = $this->workerstate[$value['location']>1?1:$value['location']];;
                $cand[4] = $value['overbeensgp']==0?"Y":"N";
                $cand[5] = $value['position'];
                $cand[6] = date('d-m-Y',$value['updatetime']);
                $cand[7] = $value['speciality'];
                $cand[8] = $arrStatus[$value['state']];
                $data[] = $cand;
            }

            //导出EXEL
            $this->load->library('PHPExcel');
            $this->load->library('PHPExcel/IOFactory');
            
            $objPHPExcel = new PHPExcel();
            $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
            $objPHPExcel->setActiveSheetIndex(0);
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0,1,'Name');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1,1,'Gender');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2,1,'Nationality');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3,1,'Lacation');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4,1,'Ever Bean Singapore');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5,1,'Position');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6,1,'Update Time');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7,1,'Speciality');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7,1,'Status');

            $col = 0;
            $row = 2;
            $objPHPExcel->setActiveSheetIndex(0);

            foreach ($data as $key => $value) {
                $col=0;

                foreach ($value as $k => $v) {
                    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row,$v);
                    $col++;
                }
                $row++;
            }

            $objPHPExcel->setActiveSheetIndex(0);
            $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');

            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="Candidate_'.date('Y-m-d').'.xls"');
            header('Cache-Control: max-age=0');
            $objWriter->save('php://output');
            
        }else{
            redirect('user/login');
        }
    }

    //根据查询条件导出EXCEL表
    public function export2excel2(){
        if($this->is_logged_in()){
            $searchData = $this->getSummarySearchCondition();
            
            $config = array();
            $config['per_page']    = $this->per_page;         //每页显示的数据数
            $current_page          = intval($this->input->get_post('per_page',true));  //获取当前分页页码数
            if(0 == $current_page){
               $current_page = 1;
            }
            $offset   = ($current_page - 1 ) * $config['per_page'];//设置偏移量 限定 数据查询 起始位置（从 $offset 条开始）

            $summary  = $this->reminder_model->get_summary_export($searchData);
            $passtype = $this->passtype;
            $status   = $this->profilestatus;
            
            $rs = $summary['res'];
            foreach ($rs as $key => $value) {
                $remd[0] = $value['name'];
                $remd[1] = $value['workname'];
                $remd[2] = isset($value['worktype'])?$passtype[$value['worktype']]:'';
                $remd[3] = $status[$value['status']];
                //申请时间
                if($searchData['status']==1){
                    $remd[4] = ($value['applytime'] != NULL&&$value['applytime'] != '')?date('Y-m-d H:m:s',$value['applytime']):'';
                }else if($searchData['status']==2){
                    $remd[4] = ($value['approvetime'] != NULL&&$value['approvetime'] != '')?date('Y-m-d H:m:s',$value['approvetime']):'';
                }else if($searchData['status']==3){
                    $remd[4] = ($value['arrivedtime'] != NULL&&$value['arrivedtime'] != '')?date('Y-m-d H:m:s',$value['arrivedtime']):'';
                }else if($searchData['status']==4){
                    $remd[4] = ($value['issuetime'] != NULL&&$value['issuetime'] != '')? date('Y-m-d H:m:s',$value['issuetime']): '';
                }else if($searchData['status']==5){
                    $remd[4] = ($value['returntime'] != NULL&&$value['returntime'] != '')? date('Y-m-d H:m:s',$value['returntime']): '';
                }else if($searchData['status']==6){
                    $remd[4] = ($value['rejectedtime'] != NULL&&$value['rejectedtime'] != '')? date('Y-m-d H:m:s',$value['rejectedtime']): '';
                }else if($searchData['status']==7){
                    $remd[4] = ($value['othertime'] != NULL&&$value['othertime'] != '')? date('Y-m-d H:m:s',$value['othertime']): '';
                }else if($searchData['status']==8){
                    $remd[4] = ($value['canceldate'] != NULL&&$value['canceldate'] != '')? date('Y-m-d H:m:s',$value['canceldate']): '';
                }else{
                    $remd[4] = ($value['createtime'] != NULL&&$value['createtime'] != '')? date('Y-m-d H:m:s',$value['createtime']): '';
                }
                $remd[5] = '';
                if($value['status']*1>3)
                {
                    $remd[5] = $value['wi']==0?'Y(R)':($value['wi']==1?'Y(B)':'N');
                }

                $remd[6] = '';
                if($value['status']*1>3)
                {
                    $remd[6] = $value['wici']==0?'Y(R)':($value['wici']==1?'Y(B)':'N');
                }
                $remd[7] = $value['username'];
                $remd[8] = $value['employeename'];
                $data[] = $remd;
            }
            //导出EXEL
            $this->load->library('PHPExcel');
            $this->load->library('PHPExcel/IOFactory');
            
            $objPHPExcel = new PHPExcel();
            $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
            $objPHPExcel->setActiveSheetIndex(0);
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0,1,'Company Name');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1,1,'Worker Name');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2,1,'Permit type');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3,1,'Stats');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4,1,'Create Date');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5,1,'MI');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6,1,'WICI');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7,1,'Salseman');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(8,1,'Interviewer');

            $col = 0;
            $row = 2;
            $objPHPExcel->setActiveSheetIndex(0);

            foreach ($data as $key => $value) {
                $col=0;

                foreach ($value as $k => $v) {
                    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row,$v);
                    $col++;
                }
                $row++;
            }

            $objPHPExcel->setActiveSheetIndex(0);
            $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');

            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="Report_'.date('Y-m-d').'.xls"');
            header('Cache-Control: max-age=0');
            $objWriter->save('php://output');

            //var_dump($data[0]);exit;
        }else{
            redirect('user/login');
        }
    }
    
    public function company(){
        if($this->is_logged_in()){
            $config = array();
            $config['per_page']    = $this->per_page;         //每页显示的数据数
            $current_page          = intval($this->input->get_post('per_page',true));  //获取当前分页页码数
            $condition = $this->input->post('condition') == NULL?
                    $this->input->get('condition'):$this->input->post('condition');
            if(0 == $current_page){
               $current_page = 1;
            }
            $ordername = ($this->input->post('ordername') != NULL&&$this->input->post('ordername') != "")
                    ?$this->input->post('ordername'):
                        (($this->input->get('ordername') != NULL&&$this->input->get('ordername') != "")
                            ?$this->input->get('ordername'):"c.updatetime desc");
            $offset   = ($current_page - 1 ) * $config['per_page'];          //设置偏移量 限定 数据查询 起始位置（从 $offset 条开始）       
            $candidate  = $this->index_model->get_campany($offset,$config['per_page'],$ordername,$condition);
            $config['base_url']           = base_url('index/company?').'condition='.$condition."&ordername=".$ordername."&";
            $config['prev_link']          = $this->prev_link;
            $config['next_link']          = $this->next_link;
            $config['total_rows']         = $candidate['total'];         //获取查询数据的总记录数
            $config['use_page_numbers']   = TRUE;            //默认分页URL中是显示每页记录数,启用use_page_numbers后显示的是当前页码
            $config['page_query_string']  = TRUE;            //把 $config['enable_query_strings'] 设置为 TRUE，链接将自动地被用查询字符串（url中的参数）重写。        
            $this->pagination->initialize($config);

            $data = array(
                'companys'  => $candidate['res'],
                'total'   => $candidate['total'],
                'current_page' => $current_page,
                'per_page'  => $config['per_page'],
                'page'   => $this->pagination->create_links(),
                'condition'  =>  $condition,
                'ordername'=>$ordername
            );
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/company',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }
    
    public function industry(){
        if($this->is_logged_in()){
            $data['condition'] = $this->input->post("condition");
            $data['industry']  = $this->index_model->get_industry($data['condition']);
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/industry',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }
    
    public function newindustry(){
        $this->form_validation->set_rules('industry', 'Industry', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data['condition'] = $this->input->post("condition");
            $data['industry']  = $this->index_model->get_industry($data['condition']);
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/industry',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            $this->index_model->newindustry();
            redirect("index/industry");
        }
    }
    
    public function new_candidate(){
        $this->form_validation->set_rules('name', 'Worker Name', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data['intermediary'] = $this->index_model->getcompanybytype(2);
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/newcandidate',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            $id = $this->index_model->newcandidate();
            if($id != NULL && $id > 0){
                $config['upload_path'] = './resource/uploadfile/';
                $config['allowed_types']    = 'gif|jpg|png|jpeg|doc|docx';
                $this->load->library('upload', $config);
                if ($this->upload->do_upload('workeric')){
                    $udata = $this->upload->data();
                    $resumefile = $udata['file_name'];
                    $this->index_model->addfile("workerIC",$resumefile,$id,0);
                }
                if ($this->upload->do_upload('resume')){
                    $udata = $this->upload->data();
                    $resumefile = $udata['file_name'];
                    $this->index_model->addfile("resume",$resumefile,$id,0);
                }
                if ($this->upload->do_upload('diploma')){
                    $udata = $this->upload->data();
                    $diplomafile = $udata['file_name'];
                    $this->index_model->addfile("diploma",$diplomafile,$id,0);
                }
                if ($this->upload->do_upload('passport')){
                    $udata = $this->upload->data();
                    $passportfile = $udata['file_name'];
                    $this->index_model->addfile("passport",$passportfile,$id,0);
                }
            }
            redirect("index/index");
        }
    }
    
    public function new_company(){
        $this->form_validation->set_rules('name', 'Company name', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data['industry']  = $this->index_model->get_industry("");
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/newcompany',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            $this->index_model->newcompany();
            redirect("index/company");
        }
    }
    
    public function deletecandidate(){
        $this->index_model->deletecandidate();
        redirect("index/index");
    }
    
    public function deletecompany(){
        $this->index_model->deletecompany();
        redirect("index/company");
    }
    
    public function candidate_detail($id){
        $this->form_validation->set_rules('name', 'Candidate name', 'trim|required');
        if (!$_POST) {
            $data['candidate'] = $this->index_model->getcandidatebyid($id);
            $data['candidate']['employeename'] = $this->user_model->getuserbyid($data['candidate']['employeeid']);
            $data['thisintermediary'] = $this->index_model->getcompanybyid($data['candidate']['companyid']);
            if(count($data['thisintermediary']) == 0){
                $data['thisintermediary']['name'] = "";
            }
            $data['attachments'] = $this->index_model->getAttachmentsBYAssociatedID($id);
            $data['intermediary'] = $this->index_model->getcompanybytype(2);
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/candidate_detail',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            $this->index_model->updatecandidate($id);
            redirect("index/index");
        }
    }
    
    function downfile($file){
        $file = base_url()."/resource/uploadfile/".$file;
        Header("HTTP/1.1 303 See Other"); 
        Header("Location: $file"); 
        exit; 
    }
    
    public function deleteindustry(){
        $this->index_model->deleteindustry();
        redirect("index/industry");
    }
    
    public function company_detail($id){
        $data['company'] = $this->index_model->getcompanybyid($id);
        $data['industry']  = $this->index_model->get_industry("");
        $data['marketing'] = $this->user_model->getMarketing();
        $data['attachments'] = $this->index_model->getAttachmentsBYAssociatedID($id,9);
        $this->load->view('templates/header');
        $this->load->view('templates/left');
        $this->load->view('index/index_top');
        $this->load->view('index/companydetail',$data);
        $this->load->view('index/index_bottom');
        $this->load->view('templates/footer');
    }
    
    public function update_company(){
        $this->form_validation->set_rules('name', 'Company name', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data['company'] = $this->index_model->getcompanybyid($id);
            $data['industry']  = $this->index_model->get_industry("");
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/companydetail',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            $this->index_model->updatecompany();
            redirect("index/company");
        }
    }
    
    
    
    public function intermediary(){
        if($this->is_logged_in()){
            $config = array();
            $config['per_page']    = $this->per_page;         //每页显示的数据数
            $current_page          = intval($this->input->get_post('per_page',true));  //获取当前分页页码数
            $condition = $this->input->post('condition') == NULL?
                    $this->input->get('condition'):$this->input->post('condition');
            if(0 == $current_page){
               $current_page = 1;
            }
            $ordername = ($this->input->post('ordername') != NULL&&$this->input->post('ordername') != "")
                    ?$this->input->post('ordername'):
                        (($this->input->get('ordername') != NULL&&$this->input->get('ordername') != "")
                            ?$this->input->get('ordername'):"updatetime desc");
            $offset   = ($current_page - 1 ) * $config['per_page'];          //设置偏移量 限定 数据查询 起始位置（从 $offset 条开始）       
            $candidate  = $this->index_model->get_intermediary($offset,$config['per_page'],$ordername,$condition);
            $config['base_url']           = base_url('index/intermediary?').'condition='.$condition."&ordername=".$ordername."&";
            $config['prev_link']          = $this->prev_link;
            $config['next_link']          = $this->next_link;
            $config['total_rows']         = $candidate['total'];         //获取查询数据的总记录数
            $config['use_page_numbers']   = TRUE;            //默认分页URL中是显示每页记录数,启用use_page_numbers后显示的是当前页码
            $config['page_query_string']  = TRUE;            //把 $config['enable_query_strings'] 设置为 TRUE，链接将自动地被用查询字符串（url中的参数）重写。        
            $this->pagination->initialize($config);

            $data = array(
                'intermediary'  => $candidate['res'],
                'total'   => $candidate['total'],
                'current_page' => $current_page,
                'per_page'  => $config['per_page'],
                'page'   => $this->pagination->create_links(),
                'condition'  =>  $condition,
                'ordername'=>$ordername
            );
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/intermediary',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }
    
    public function new_intermediary(){
        $this->form_validation->set_rules('name', 'Intermediary name', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/newintermediary');
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            $this->index_model->newintermediary();
            redirect("index/intermediary");
        }
    }
    
    public function delete_intermediary(){
        $this->index_model->delete_intermediary();
        redirect("index/intermediary");
    }
    
    public function intermediary_detail($id){
        $this->form_validation->set_rules('name', 'Intermediary name', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data['company'] = $this->index_model->getcompanybyid($id);
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/intermediary_detail',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            $this->index_model->updateintermediary($id);
            redirect("index/intermediary");
        }
    }
    
    
    
    public function houseagency(){
        if($this->is_logged_in()){
            $config = array();
            $config['per_page']    = $this->per_page;         //每页显示的数据数
            $current_page          = intval($this->input->get_post('per_page',true));  //获取当前分页页码数
            $condition = $this->input->post('condition') == NULL?
                    $this->input->get('condition'):$this->input->post('condition');
            if(0 == $current_page){
               $current_page = 1;
            }
            $ordername = ($this->input->post('ordername') != NULL&&$this->input->post('ordername') != "")
                    ?$this->input->post('ordername'):
                        (($this->input->get('ordername') != NULL&&$this->input->get('ordername') != "")
                            ?$this->input->get('ordername'):"name desc");
            $offset   = ($current_page - 1 ) * $config['per_page'];          //设置偏移量 限定 数据查询 起始位置（从 $offset 条开始）       
            $candidate  = $this->index_model->get_houseagency($offset,$config['per_page'],$ordername,$condition);
            $config['base_url']           = base_url('index/houseagency?').'condition='.$condition."&ordername=".$ordername."&";
            $config['prev_link']          = $this->prev_link;
            $config['next_link']          = $this->next_link;
            $config['total_rows']         = $candidate['total'];         //获取查询数据的总记录数
            $config['use_page_numbers']   = TRUE;            //默认分页URL中是显示每页记录数,启用use_page_numbers后显示的是当前页码
            $config['page_query_string']  = TRUE;            //把 $config['enable_query_strings'] 设置为 TRUE，链接将自动地被用查询字符串（url中的参数）重写。        
            $this->pagination->initialize($config);

            $data = array(
                'houseagency'  => $candidate['res'],
                'total'   => $candidate['total'],
                'current_page' => $current_page,
                'per_page'  => $config['per_page'],
                'page'   => $this->pagination->create_links(),
                'condition'  =>  $condition,
                'ordername'=>$ordername
            );
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/houseagency',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }
    
    public function new_houseagency(){
        $this->form_validation->set_rules('name', 'House Agency name', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/newhouseagency');
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            $this->index_model->newhouseagency();
            redirect("index/houseagency");
        }
    }
    
    public function delete_houseagency(){
        $this->index_model->delete_houseagency();
        redirect("index/houseagency");
    }
    
    public function houseagency_detail($id){
        $this->form_validation->set_rules('name', 'House Agency name', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data['company'] = $this->index_model->getcompanybyid($id);
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('index/houseagency_detail',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            $this->index_model->updatehouseagency($id);
            redirect("index/houseagency");
        }
    }
    
    public function newattachment($associatedid,$associatedtype=0){
        $config['upload_path'] = './resource/uploadfile/';
        $config['allowed_types']    = 'gif|jpg|png|jpeg|doc|docx|word|pdf|xlsx|xl';
        $config['max_size'] = 0;
        $this->load->library('upload', $config);
        if ($this->upload->do_upload('path')){
            $udata = $this->upload->data();
            $resumefile = $udata['file_name'];
            $type = $this->input->post("type") == NULL?0:$this->input->post("type");
            $this->index_model->addfile($this->input->post("title"),$resumefile,$associatedid,$associatedtype,$type);
            if($associatedtype == 0){
                redirect("index/candidate_detail/".$associatedid);
            }else if($associatedtype == 9){
                redirect("index/company_detail/".$associatedid);
            }else{
                redirect("profile/detail_profile/".$associatedid);
            }
        }else{
            $error = array('error' => $this->upload->display_errors());
            $udata = $this->upload->data();
            var_dump($error);
            var_dump($udata);
        }
    }
    
    public function deleteattachment($id,$workerid){
        $this->index_model->deleteAttachments($id);
        redirect("index/candidate_detail/".$workerid);
    }
    
    public function deleteattachment2($id,$profileid){
        $this->index_model->deleteAttachments($id);
        redirect("profile/detail_profile/".$profileid);
    }
    
    public function uploadCandidate(){
        if (!empty($_FILES)) {
            $tempFile = $_FILES['Filedata']['tmp_name'];
            $suffix = substr($_FILES['Filedata']['name'],strripos($_FILES['Filedata']['name'],'.'));
            $finelName = time().$suffix;
            $targetFile =  './resource/excel/'.$finelName;
            $flag = move_uploaded_file($tempFile,$targetFile);
            if($flag){
                $this->excel_fileput($finelName);
            }else{
                echo '上传失败';
            }
        }else{
            echo '上传出错';
        }
    }
    
    public function excel_fileput($finelName){
        $filePath = "resource/excel/".$finelName;
        $this->load->library("PHPExcel");//ci框架中引入excel类
        $PHPExcel = new PHPExcel();
        $PHPReader = new PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($filePath)){
            $PHPReader = new PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($filePath)){
                echo '请选择excel文件';
                return ;
            }
        }
        // 加载excel文件
        $PHPExcel = $PHPReader->load($filePath);
        // 读取excel文件中的第一个工作表
        $currentSheet = $PHPExcel->getSheet(0);
        // 取得最大的列号
        $allColumn = $currentSheet->getHighestColumn();
        // 取得一共有多少行
        $allRow = $currentSheet->getHighestRow();
        // 从第二行开始输出，因为excel表中第一行为列名
        $dataStr = "";
        for($currentRow = 1;$currentRow <= $allRow;$currentRow++){
            for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){
                $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue();
                $dataStr .= $val;
                if($currentColumn < $allColumn){
                    $dataStr .= ',';
                }
            }
            if($currentRow < $allRow){
                $dataStr .= ';';
            }
        }
        echo $dataStr;
    }
    
    public function saveCandidate(){
        if($_POST){
            $candidateStr = $this->input->post('candidateStr');
            $candidateArr = explode(",", $candidateStr);
//            print_r($candidateArr);s
            if(count($candidateArr) == 9){
                $str = "";
                
                $data = array(
                    'name'=>$candidateArr[0],
                    'gender'=>$candidateArr[1]=='M'?0:1,
                    'nationality'=>$candidateArr[2]=='Malaysia'?1:($candidateArr[2]=='China'?2:($candidateArr[2]=='Vietnam'?3:($candidateArr[2]=='Myanmar'?4:6))),
                    'birthday'=>$candidateArr[3],
                    'position'=>$candidateArr[4],
                    'speciality'=>$candidateArr[5],
                    'workaddress'=>$candidateArr[6],
                    'location'=>$candidateArr[7]=='singapore'?1:0,
                    'comment'=>$candidateArr[8],
                    'employeeid' => $this->session->userdata('user')->id,
                    'createtime'=>time(),
                    'updatetime'=>time()
                );
                
                $id = $this->profile_model->create("workers",$data);
                if($id&&$id>0){
                    $str .= "&nbsp;&nbsp;<a style='color:green;'>新增工人:".$candidateArr[0].'成功</a>;<br/>';
                }else{
                    $str .= "&nbsp;&nbsp;<a style='color:red;'>新增工人:".$candidateArr[0].'失败</a>;<br/>';
                }
                $str .= "&nbsp;&nbsp;<a style='color:green;'>------结束------</a>;<br/>";
                echo $str;
            }
        }else{
            echo 0;
        }
    }
}